package com.starbaba.system.roleofmenu.dao;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;

import com.starbaba.core.hibernate.DAOFactory;
import com.starbaba.core.hibernate.HibernateDAO;
import com.starbaba.core.hibernate.Strategy;
import com.starbaba.core.web.constant.WebConstants;
import com.starbaba.system.roleofmenu.model.RoleOfMenuVO;
import com.starbaba.system.user.model.UserVO;

@SuppressWarnings("serial")
public class SaveRoleOfMenuStrategy implements Strategy{
	
	private Long roleId;
	private String[] menuIds;
	private UserVO userVO;
	
	public SaveRoleOfMenuStrategy(Long roleId, String[] menuIds, UserVO userVO) {
		super();
		this.roleId = roleId;
		this.menuIds = menuIds;
		this.userVO = userVO;
	}

	@Override
	@SuppressWarnings("unchecked")
	public Object process() throws Exception {
		
		HibernateDAO dao = DAOFactory.getInstance().createHibernateDAO(RoleOfMenuVO.class);
		List<RoleOfMenuVO> orgList = (List<RoleOfMenuVO>) dao.findByProperty("roleId", roleId);
		Map<String, Long> orgMap = new HashMap<String, Long>();
		for(RoleOfMenuVO roleOfMenuVO : orgList){
			orgMap.put(roleOfMenuVO.getMenuId(), roleOfMenuVO.getRoleId());
		}
		orgList = null;
		Map<String, Long> destMap = new HashMap<String, Long>();
		for(String menuId : menuIds){
			if(StringUtils.isNotBlank(menuId)){
				destMap.put(menuId, roleId);
			}
		}
		//首先处理收回的权限记录
		for(Map.Entry<String, Long> entry : orgMap.entrySet()){
			String thMenuId = entry.getKey();
			Long thRoleId = entry.getValue();
			if(!destMap.containsKey(thMenuId)){
				RoleOfMenuVO roleofmenuVO = new RoleOfMenuVO(thRoleId, thMenuId);
				dao.deleteByPK(roleofmenuVO);
			}
		}
		//处理新增权限记录
		for(Map.Entry<String, Long> entry : destMap.entrySet()){
			String thMenuId = entry.getKey();
			Long thRoleId = entry.getValue();
			if(!orgMap.containsKey(thMenuId)){
				RoleOfMenuVO roleofmenuVO = new RoleOfMenuVO(thRoleId, thMenuId,WebConstants.GRADE_HIGH);
				dao.save(roleofmenuVO);
			}
		}
		return null;
	}


	public Long getRoleId() {
		return roleId;
	}

	public void setRoleId(Long roleId) {
		this.roleId = roleId;
	}

	public String[] getMenuIds() {
		return menuIds;
	}

	public void setMenuIds(String[] menuIds) {
		this.menuIds = menuIds;
	}

	/**
	 * @return userVO
	 */
	
	public UserVO getUserVO() {
		return userVO;
	}

	/**
	 * @param userVO the userVO to set
	 */
	public void setUserVO(UserVO userVO) {
		this.userVO = userVO;
	}



}
